package com.zjb.demo.system.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.mybatisflex.core.paginate.Page;
import com.zjb.demo.common.domain.dto.SysLoginInfo;
import com.zjb.demo.common.domain.response.AjaxResult;
import com.zjb.demo.system.domain.SysDictData;
import com.zjb.demo.system.domain.query.SysDictDataQuery;
import com.zjb.demo.system.service.SysDictDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Context;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * @author 庄佳彬
 * @since 2023/12/28 09:19
 */
@Controller
@Mapping("/system/dict/data")
@Api(tags = "字典数据")
public class SysDictDataController {
    @Inject
    private SysDictDataService dataService;

    @Get
    @Mapping("/list")
    @ApiOperation(value = "字典数据列表")
    public AjaxResult<Page<SysDictData>> list(SysDictDataQuery query) {
        return AjaxResult.success(dataService.pageList(query));
    }

    @Get
    @Mapping("/export")
    @ApiOperation(value = "导出字典数据")
    public void export(SysDictDataQuery query) throws IOException {
        var list = dataService.list(query);
        var ctx = Context.current();
        ctx.contentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        ctx.headerAdd("Content-Disposition", "attachment;filename=" + URLEncoder.encode("字典", StandardCharsets.UTF_8) + DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xlsx");
        var os = ctx.outputStream();
        EasyExcel.write(os, SysLoginInfo.class)
                .sheet("字典")
                .doWrite(list);
    }

    @Get
    @Mapping("/{dictCode}")
    @ApiOperation(value = "根据字典编号获取详细信息")
    public AjaxResult<SysDictData> detail(Long dictCode) {
        return AjaxResult.success(dataService.getById(dictCode));
    }

    @Get
    @Mapping(value = "/type/{dictType}")
    @ApiOperation(value = "根据字典类型查询字典数据信息")
    public AjaxResult<List<SysDictData>> dictType(String dictType) {
        return AjaxResult.success(dataService.selectDictDataByType(dictType));
    }

    @Post
    @Mapping
    @ApiOperation(value = "添加字典数据")
    public AjaxResult<Boolean> add(@Body SysDictData data) {
        return AjaxResult.success(dataService.insertAndCache(data));
    }

    @Put
    @Mapping
    @ApiOperation(value = "修改字典数据")
    public AjaxResult<Boolean> edit(@Body SysDictData data) {
        return AjaxResult.success(dataService.updateAndCache(data));
    }

    @Delete
    @Mapping("/{dictCodes}")
    @ApiOperation(value = "删除字典数据")
    public AjaxResult<Void> delete(Long[] dictCodes) {
        dataService.deleteAndCache(dictCodes);
        return AjaxResult.success();
    }
}
